package com.itheima.exceptionResolver;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.entity.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    @ResponseBody
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.setContentType("text/html;charset=UTF-8");
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            ExceptionMessage annotation = method.getAnnotation(ExceptionMessage.class);
            if (annotation!=null){
                String value = annotation.value();
                Result result = new Result(false, value);
                String resultJson = JSONObject.toJSONString(result);
                try {
                    response.getWriter().write(resultJson);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ModelAndView mv=new ModelAndView();
        return mv;
    }


//    public Result handleException(RuntimeException e) {
//        ExceptionMessage annotation = ExceptionResolver.class.getAnnotation(ExceptionMessage.class);
//        System.out.println(annotation.value());
//        return new Result(false,"处理异常,请稍后" );
//
//    }
}
